package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constans.user.AdminConstans;
import com.heima.common.exception.CustomException;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.media.pojos.WmUser;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.user.feign.ArticleFeign;
import com.heima.user.feign.WemediaFeign;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;


@Service
@Transactional
@Slf4j
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {

    @Autowired
    ApUserMapper apUserMapper;

    @Autowired
    WemediaFeign wemediaFeign;

    @Autowired
    ArticleFeign articleFeign;

    @Override
    public ResponseResult findListByStatus(AuthDto dto) {

        //1.检查参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();

        //2.封装条件
        Page<ApUserRealname> pageRequest = new Page<>(dto.getPage(), dto.getSize());

        LambdaQueryWrapper<ApUserRealname> queryWrapper = Wrappers.<ApUserRealname>lambdaQuery();

        if (dto.getStatus() !=null){
            queryWrapper.eq(ApUserRealname::getStatus,dto.getStatus());
        }

        //3.执行查询
        IPage<ApUserRealname> pageResult = page(pageRequest, queryWrapper);

        //4.封装接口返回
        ResponseResult responseResult = new PageResponseResult(dto.getSize(),dto.getPage(),pageResult.getTotal());
        responseResult.setData(pageResult.getRecords());

        return responseResult;
    }

    /**
     *
     * @param dto  status(2 失败，9 通过) id msg 失败原因
     * @return
     */
    @GlobalTransactional
    @Override
    public ResponseResult updateByStatus(AuthDto dto) {

        //1.检查参数
        if (dto==null&&dto.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        if (!checkStatus(dto.getStatus())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.根据id修改ap_user_realname表的status
        ApUserRealname apUserRealname=new ApUserRealname();

        apUserRealname.setId(dto.getId());
        apUserRealname.setStatus(dto.getStatus());
        if (dto.getMsg()!=null){
            apUserRealname.setReason(dto.getMsg());
        }
        updateById(apUserRealname); //修改实名认证信息

        if (dto.getStatus()==AdminConstans.FAIL_AUTH){
            createWmUserAndAuthor(dto.getId());
        }

        return ResponseResult.okResult();
    }

    /**
     * 不能为空 必须是2或9
     * @return
     */
    public boolean checkStatus(Short status){
        if (status==null ||(status!= AdminConstans.FAIL_AUTH &&status!=AdminConstans.PASS_AUTH)){
            return false;
        }
        return true;
    }

    private void createWmUserAndAuthor(Integer id) {

        ApUserRealname apUserRealname = getById(id);
        Integer userId = apUserRealname.getUserId();

        ApUser apUser = apUserMapper.selectById(userId);

        if (apUser==null){
            throw new CustomException(ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"实名认证关联用户信息不存在"));
        }
        //3.1 查询自媒体用户是否存在  如果不存在 创建Wmuser 保存
        WmUser wmUser = wemediaFeign.findByName(apUser.getName());

        if (wmUser==null){
            wmUser=new WmUser();
            wmUser = new WmUser();
            wmUser.setApUserId(apUser.getId());
            wmUser.setName(apUser.getName());
            wmUser.setPassword(apUser.getPassword());
            wmUser.setSalt(apUser.getSalt());
            wmUser.setImage(apUser.getImage());
            wmUser.setPhone(apUser.getPhone());
            wmUser.setStatus(9);
            wmUser.setCreatedTime(new Date());
            wemediaFeign.save(wmUser);
        }
        //3.2 查询作者信息是否存在  如果不存在 创建ApAuthor 保存
        createAuthor(wmUser);
    }

    private void createAuthor(WmUser wmUser){

        ApAuthor apAuthor = articleFeign.findByUserId(wmUser.getApUserId());

        if (apAuthor==null){
            apAuthor=new ApAuthor();
            apAuthor.setName(wmUser.getName());
            apAuthor.setType(2);
            apAuthor.setCreatedTime(new Date());
            apAuthor.setUserId(wmUser.getApUserId());
            apAuthor.setWmUserId(wmUser.getId());
            articleFeign.save(apAuthor);
        }
    }
}
